package com.wichell.framework.rocketmq.example.transaction;

import java.util.Date;
import java.util.Random;

import org.apache.rocketmq.client.producer.LocalTransactionExecuter;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.common.message.Message;

/**
 * 执行本地事务 如果事务消息发送到MQ上后，会回调该执行器
 */
public class TransactionExecuterImpl implements LocalTransactionExecuter {

	@Override
	public LocalTransactionState executeLocalTransactionBranch(final Message msg, final Object arg) {
		try {
			System.out.println(msg.toString());
			System.out.println("msg = " + new String(msg.getBody()));
			// System.out.println("arg = " + arg);
			System.out.println("这里执行入库操作....入库成功");
			if (new Random().nextInt(2) == 1) {
			}
			System.out.println(new Date() + "本地事务执行成功，发送确认消息");
			// return LocalTransactionState.COMMIT_MESSAGE;
		} catch (Exception e) {
			System.err.println(new Date() + "本地事务执行失败");
			return LocalTransactionState.UNKNOW;
		}
		// 下面两者情况的返回将不会被消费者读取到
		// LocalTransactionState.ROLLBACK_MESSAGE LocalTransactionState.UNKNOW
		return LocalTransactionState.COMMIT_MESSAGE;
	}
}